package com.example.myapplication.ui.fragments;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.myapplication.databinding.FragmentGreenDaoBinding;
import com.example.myapplication.mgreendao.pojo.DBManager;
import com.example.myapplication.mgreendao.pojo.StudentGreen;
import com.example.myapplication.mgreendao.pojo.UserGreen;
import com.test.greendao.StudentGreenDao;
import com.test.greendao.UserGreenDao;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.fragment.app.Fragment;


public class GreenDaoFragment extends Fragment {
    private static final String TAG = "GreenDaoFragment";

    private final ExecutorService executorService = Executors.newFixedThreadPool(2);
    private FragmentGreenDaoBinding binding;
    private  volatile UserGreenDao userGreenDao;
    private volatile StudentGreenDao studentGreenDao;
    private int num;

    public GreenDaoFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentGreenDaoBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        userGreenDao = DBManager.getDaoSession(requireActivity().getApplication()).getUserGreenDao();
        studentGreenDao = DBManager.getDaoSession(requireActivity().getApplication()).getStudentGreenDao();

        //增
        binding.btns.insert.setOnClickListener(v -> {
            greenDaoInsert();
        });

        binding.btns.delete.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    userGreenDao.deleteByKey((long) num);
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "GreenDao删除一条数据耗时---->" + endTime + "ms");
                    addView("GreenDao删除一条耗时："+endTime+"ms");
                }
            });
        });

        binding.btns.update.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    UserGreen name222220 = new UserGreen();
                    name222220.setId((long) num);
                    name222220.setName("name");
                    long startTime = System.currentTimeMillis();
                    userGreenDao.update(name222220);
//                    userGreenDao.updateInTx();
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "GreenDao更新一条数据耗时---->" + endTime + "ms");
                    addView("GreenDao更新一条耗时："+endTime+"ms");
                }
            });
        });

        binding.btns.query.setOnClickListener(v -> {
            Executors.newSingleThreadExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    userGreenDao.loadAll();
//                    Cursor cursor = userGreenDao.getDatabase().rawQuery("select * from user_green", null);
//                    userGreenDao.queryRaw()
                    long endTime = (System.currentTimeMillis() - startTime);
                    Log.e(TAG, "GreenDao查询所有数据耗时---->" + endTime + "ms");
                    addView("GreenDao查询所有耗时："+endTime+"ms");
                }
            });
        });

        binding.edtInput.input.addTextChangedListener(new TextWatcher() {
            boolean isEdt;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (isEdt)return;
                isEdt = true;
                String str =editable.toString().replace("/^0*/g", "");
                if (!str.equals("")){
                    int i = Integer.parseInt(str);
                    if (i != 0) num = i;
                }
                isEdt = false;
            }
        });

        //多线程多表单表
        final boolean isOpen = true; //true多表操作
        binding.btns.manyInsert.setOnClickListener(v -> {

            if (isOpen){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<UserGreen> mySportsList = new ArrayList<>();
                        for (int i = 0; i < 10000; i++) {
                            UserGreen mySports = new UserGreen();
                            mySports.setName("name" + i);
                            mySports.setMoney(222);
                            mySportsList.add(mySports);
                        }
                        long startTime = System.currentTimeMillis();
                        userGreenDao.insertInTx(mySportsList);
                        long endTime = (System.currentTimeMillis() - startTime);
                        addView("线程"+Thread.currentThread().getId()+"插入user表耗时："+endTime+"ms");
                    }
                });
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<StudentGreen> mySportsList = new ArrayList<>();
                        for (int i = 0; i < 10000; i++) {
                            StudentGreen mySports = new StudentGreen();
                            mySports.setName("name" + i);
                            mySportsList.add(mySports);
                        }
                        long startTime = System.currentTimeMillis();
                        studentGreenDao.insertInTx(mySportsList);
                        long endTime = (System.currentTimeMillis() - startTime);
                        addView("线程"+Thread.currentThread().getId()+"插入student表耗时："+endTime+"ms");
                    }
                });
            }else {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<UserGreen> mySportsList = new ArrayList<>();
                        for (int i = 0; i < 10000; i++) {
                            UserGreen mySports = new UserGreen();
                            mySports.setName("name" + i);
                            mySports.setMoney(222);
                            mySportsList.add(mySports);
                        }
                        long startTime = System.currentTimeMillis();
                        userGreenDao.insertInTx(mySportsList);
                        long endTime = (System.currentTimeMillis() - startTime);
                        addView("线程"+Thread.currentThread().getId()+"插入user表耗时："+endTime+"ms");
                    }
                });
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<UserGreen> mySportsList = new ArrayList<>();
                        for (int i = 0; i < 10000; i++) {
                            UserGreen mySports = new UserGreen();
                            mySports.setName("name" + i);
                            mySports.setMoney(222);
                            mySportsList.add(mySports);
                        }
                        long startTime = System.currentTimeMillis();
                        userGreenDao.insertInTx(mySportsList);
                        long endTime = (System.currentTimeMillis() - startTime);
                        addView("线程"+Thread.currentThread().getId()+"插入user表耗时："+endTime+"ms");
                    }
                });
            }

        });

        binding.btns.manyQuery.setOnClickListener(v -> {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    userGreenDao.loadAll();
                    long endTime = (System.currentTimeMillis() - startTime);
                    addView("线程"+Thread.currentThread().getId()+"查询user表耗时："+endTime+"ms");
                }
            });

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    long startTime = System.currentTimeMillis();
                    studentGreenDao.loadAll();
                    long endTime = (System.currentTimeMillis() - startTime);
                    addView("线程"+Thread.currentThread().getId()+"查询student表耗时："+endTime+"ms");
                }
            });
        });

    }

    public void greenDaoInsert() {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                List<UserGreen> mySportsList = new ArrayList<>();
                for (int i = 0; i < 100000; i++) {
                    UserGreen mySports = new UserGreen();
                    mySports.setName("name" + i);
                    mySports.setMoney(222);
                    mySportsList.add(mySports);
                }
                long startTime = System.currentTimeMillis();
                userGreenDao.insertInTx(mySportsList);
                long endTime = (System.currentTimeMillis() - startTime);
                Log.e(TAG, "Greendao插入10w数据耗时---->" +endTime + "ms");
                addView("GreenDao插入10w耗时："+endTime+"ms");
            }
        });
    }


    private void addView(String string) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = new TextView(requireActivity());
                textView.setText(string);
                textView.setTextSize(20);
                ((LinearLayoutCompat) binding.texts.textss).addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (binding != null)
            binding = null;
        if (executorService!=null)executorService.shutdown();
    }
}